<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/4/29 9:57
 * Remark:
 */

namespace App\ServiceChecker\Approval;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Models\Approval\OldDingTalkApprovalTemplateModel;
use App\Models\CreditProject\CreditProjectModel;
use App\ServiceChecker\BasicServiceChecker;
use Illuminate\Http\Exceptions\HttpResponseException;

class ApprovalLegitimacy extends BasicServiceChecker
{
    private CreditProjectModel $_creditProjectModel;
    private OldDingTalkApprovalTemplateModel $_oldDingTalkApprovalTemplateModel;

    public function __construct()
    {
        parent::__construct();
        $this->_creditProjectModel = new CreditProjectModel();
        $this->_oldDingTalkApprovalTemplateModel = new OldDingTalkApprovalTemplateModel();
    }

    /**
     * 检测合同模板使用情况
     * @param $companyId
     * @param $templateCode
     */
    public function verifyCompanyApprovalTemplateIsExists($companyId,$templateCode){
        $isExist = $this->_oldDingTalkApprovalTemplateModel->isExistByCondition([
            'company_id' => $companyId,
            'ding_talk_approval_template_code' => $templateCode,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if($isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "当前合同模板已被使用",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }

    /**
     * @param $approvalTemplateId
     */
    public function verifyApprovalTemplateIsExists($approvalTemplateId){
        $isExist = $this->_oldDingTalkApprovalTemplateModel->isExistByCondition([
            'ding_talk_approval_template_id' => $approvalTemplateId,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if(!$isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "当前模板不存在或已删除",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }

    public function verifyCreditProjectTotalIsGrClientCreditTotal($clientId,$creditClientLimit){
        $projectTotal =  $this->_creditProjectModel->getCreditProjectTotal($clientId);
        if($creditClientLimit < $projectTotal){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "已有信用项目额度大于客户额度",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }
}